const { fileUpload, deleteFile } = require('../../utils/files.js')

const adminUploadFile = async (request, reply) => {
  const data = await request.file()
  if (!data.filename) {
    return reply.code(400).send({
      message: '未找到上传文件！',
      data: null,
      code: reply.statusCode,
      error: data.fieldname + '不能为空!',
    })
  }
  const setResult = await fileUpload(data, data.fieldname, data.fieldname)

  const datas = {
    url: setResult.data.fileUrl,
    name: setResult.data.fileName,
    filePath: setResult.data.filePath,
    uid: setResult.data.fileTimeName,
  }
  return reply.code(200).send({
    data: datas,
    code: reply.statusCode,
  })
}
const adminDeleteFile = async (request, reply) => {
  const { uid, filePath } = request.query
  const result = await deleteFile('admin', filePath, uid)
  if (result.code === 200) {
    return reply.code(200).send({
      ...result,
    })
  }
  return reply.send({
    ...result,
  })
}

const wechatUploadFile = async (request, reply) => {
  const data = await request.file()
  if (!data.filename) {
    return reply.code(400).send({
      message: '未找到上传文件！',
      data: null,
      code: reply.statusCode,
      error: data.fieldname + '不能为空!',
    })
  }
  const setResult = await fileUpload(data, 'wechat', data.fieldname)

  const datas = {
    url: setResult.data.fileUrl,
    name: setResult.data.fileName,
    filePath: setResult.data.filePath,
    uid: setResult.data.fileTimeName,
  }
  return reply.code(200).send({
    data: datas,
    code: reply.statusCode,
  })
}
const wechatDeleteFile = async (request, reply) => {
  const { uid, filePath } = request.body
  const result = await deleteFile('wechat', filePath, uid)
  if (result.code === 200) {
    return reply.code(200).send({
      ...result,
    })
  }
  return reply.send({
    ...result,
  })
}

module.exports = {
  wechatUploadFile,
  wechatDeleteFile,
  adminUploadFile,
  adminDeleteFile,
}
